package com.heima.article.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.article.service.ArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService{

    @Resource
    private Configuration configuration;
    @Resource
    private FileStorageService fileStorageService;
    @Resource
//    private ArticleService articleService;
    private ApArticleMapper apArticleMapper;
    @Resource
    private KafkaTemplate<String, String> kafkaTemplate;


    /**
     * 生成静态文件上传到minIO中
     */
    @Async
    @Override
    public void buildArticleToMinIO(ApArticle apArticle, String content) {
        if (StrUtil.isEmpty(content)) {
            return;
        }
        //文章内容通过freemarker生成html文件
        Template template;
        StringWriter out = new StringWriter();
        try {
            template = configuration.getTemplate("templates/article.ftl");
            //数据模型
            Map<String, Object> contentDataModel = new HashMap<>();
            contentDataModel.put("content", JSONArray.parseArray(content));
            //合成
            template.process(contentDataModel, out);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //把html文件上传到minio中
        InputStream in = new ByteArrayInputStream(out.toString().getBytes());
        String path = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", in);

        //修改ap_article表，保存static_url字段
        apArticleMapper.update(apArticle,Wrappers.<ApArticle>lambdaUpdate()
                .eq(ApArticle::getId, apArticle.getId())
                .set(ApArticle::getStaticUrl, path));

        //发送消息，创建索引
        createArticleESIndex(apArticle, content, path);
    }


    /**
     * 送消息，创建索引数据
     */
    private void createArticleESIndex(ApArticle apArticle, String content, String path) {
        SearchArticleVo vo = BeanUtil.toBean(apArticle, SearchArticleVo.class);
        vo.setContent(content);
        vo.setStaticUrl(path);
        //发消息
        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(vo));
    }

}